<?php
// +----------------------------------------------------------------------
// | 文件上传
// +----------------------------------------------------------------------
namespace app\admin\controller;
use think\facade\Db;
class Upload extends Base
{
    /**
     * @return \think\response\Json
    CREATE TABLE `sy_admin_upload_group` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `aid` int(11) DEFAULT NULL,
    `uid` int(11) DEFAULT NULL,
    `name` varchar(255) DEFAULT NULL,
    `createtime` int(11) DEFAULT NULL,
    `sort` int(11) DEFAULT '0',
    `pid` int(11) unsigned DEFAULT '0',
    PRIMARY KEY (`id`) USING BTREE,
    KEY `aid` (`aid`) USING BTREE,
    KEY `uid` (`uid`) USING BTREE
    ) ENGINE=InnoDB AUTO_INCREMENT=105 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;

    CREATE TABLE `sy_admin_upload` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `aid` int(11) DEFAULT NULL,
    `bid` int(11) DEFAULT '0',
    `uid` int(11) DEFAULT NULL,
    `name` varchar(255) DEFAULT NULL,
    `dir` varchar(255) DEFAULT NULL,
    `url` varchar(255) DEFAULT NULL,
    `type` varchar(100) DEFAULT NULL,
    `size` varchar(255) DEFAULT NULL,
    `bsize` int(11) DEFAULT NULL,
    `width` int(11) DEFAULT NULL,
    `height` int(11) DEFAULT NULL,
    `createtime` int(11) DEFAULT NULL,
    `platform` varchar(11) DEFAULT 'ht',
    `isdel` tinyint(1) DEFAULT '0',
    `gid` int(11) DEFAULT '0',
    `hash` varchar(255) DEFAULT NULL,
    PRIMARY KEY (`id`) USING BTREE,
    KEY `aid` (`aid`) USING BTREE,
    KEY `uid` (`uid`) USING BTREE,
    KEY `dir` (`dir`) USING BTREE,
    KEY `platform` (`platform`) USING BTREE,
    KEY `isdel` (`isdel`) USING BTREE,
    KEY `bid` (`bid`) USING BTREE
    ) ENGINE=InnoDB AUTO_INCREMENT=583 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;
     *
     */
	public function group(){
		$groupArr = Db::name('admin_upload_group')->where('pid',0)->order('sort desc,createtime')->column('id,name');
		if($groupArr){
            foreach ($groupArr as $k => $item){
                $children = Db::name('admin_upload_group')->where('pid',$item['id'])->order('sort desc,createtime')->column('id,name');
                $groupArr[$k]['children'] = $children ? $children : [];
            }
        }
        return json(['status'=>1,'data'=>$groupArr]);
	}
	public function addgroup(){
        $pid = input('param.pid');
		$data = [];
		$data['createtime'] = time();
		$data['name'] = input('param.name');
        $data['pid'] = $pid ? $pid : 0;
        $id = Db::name('admin_upload_group')->insertGetId($data);
        $item = Db::name('admin_upload_group')->where('id', $id)->find();
		return json(['status'=>1,'msg'=>"创建成功",'data'=>$item]);
	}
	public function editgroup(){
		$data['name'] = input('param.name');
		Db::name('admin_upload_group')->where('id',input('param.gid/d'))->update(['name'=>input('param.name')]);
		return json(['status'=>1,'msg'=>'修改成功']);
	}
	public function delgroup(){
		Db::name('admin_upload_group')->where('id',input('param.gid/d'))->delete();
		return json(['status'=>1,'msg'=>'删除成功']);
	}
	public function changegroup(){
		Db::name('admin_upload')->where('id','in',input('param.ids'))->update(['gid'=>input('param.gid/d')]);
		return json(['status'=>1,'msg'=>'移动成功']);
	}
	//上传
    public function index(){
		//var_dump();die;
		$file = request()->file('file');
		if($file){

			$maxwidth = 50;
			$maxheight = 50;
			try {
//			    $upload_type =config('app.upload_type');
//				validate(['file'=>['fileExt:'.$upload_type]])->check(['file' => $file]);
                $rinfo = [];

                $rinfo = [];
                $rinfo['extension'] = strtolower($file->getOriginalExtension());
                $rinfo['name'] = $file->getOriginalName();
                $rinfo['bsize'] = $file->getSize();
                $filesizeMb = $rinfo['bsize']/1024/1024;
                $rinfo['hash'] = $file->sha1();

                $image_upload_limit_size = config('image_upload_limit_size');
                validate(['file'=>['fileExt:'.config('app.upload_type')]])->check(['file' => $file]);
                $savename = \think\facade\Filesystem::disk('public')->putFile('',$file);
                $dir = UPLOAD_PATH;

				$filepath = '/upload/'.str_replace("\\",'/',$savename);
				$maxwidth = input('post.maxwidth') ? input('post.maxwidth') : $maxwidth;
				$maxheight = input('post.maxheight') ? input('post.maxheight') : $maxheight;


					$size = getimagesize(app()->getRootPath().'public'.$filepath);
					$rinfo['width'] = $size[0];
					$rinfo['height'] = $size[1];
					if($maxwidth > 0 && $maxheight > 0){
//						if($rinfo['width'] > $maxwidth || $rinfo['height'] > $maxheight){
//							$image = \think\Image::open(ROOT_PATH.$filepath);
//							$filepath = substr($filepath,0,strlen($filepath) - strlen($rinfo['extension']) - 1).'_thumb.'.$rinfo['extension'];
//							$image->thumb($maxwidth,$maxheight)->save(ROOT_PATH.$filepath,null,100);
//							$size = getimagesize(ROOT_PATH.$filepath);
//							$rinfo['width'] = $size[0];
//							$rinfo['height'] = $size[1];
//						}
					}

                $insert = array(
                    'name' => '',
                    'dir' => date('Ymd'),
                    'url' => '',
                    'type' => 'jpg',
                    'width' => '',
                    'height' => '',
                    'bsize' => $rinfo['bsize'],
                    'hash' => $rinfo['hash'],
                    'createtime' => time(),
                    'gid'=> cookie('browser_gid') && cookie('browser_gid')!='-1' ? cookie('browser_gid') : '0'
                );
					$domain_url = getdomain();
				$rinfo['url'] = $domain_url.ltrim($filepath,'/');
                $rinfo['url'] = logic('OssLogic')->oss_upload($rinfo['url']);
                $type_no = false;
                $rinfo['url'] = $rinfo['url'];
                $insert['name'] = $rinfo['name'];
                $insert['url'] = $rinfo['url'];
                $insert['type'] = $rinfo['extension'];
                $insert['width'] = $rinfo['width'];
                $insert['height'] = $rinfo['height'];
                $rinfo['id'] = Db::name('admin_upload')->insertGetId($insert);
                return json(['status'=>1,'state'=>'SUCCESS','msg'=>'上传成功','url'=>$rinfo['url'],'info'=>$rinfo]);
			} catch (\think\exception\ValidateException $e) {
				return json(['status'=>0,'msg'=>$e->getMessage()]);
			}
		}else{
			$errorNo = $_FILES['file']['error'];
			switch($errorNo) {
				case 1:
					$errmsg = '上传的文件超过了 upload_max_filesize 选项限制的值';break;
				case 2:
					$errmsg = '上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值';break;
				case 3:
					$errmsg = '文件只有部分被上传';break;
				case 4:
					$errmsg = '没有文件被上传';break;
				case 6:
					$errmsg = '找不到临时文件夹';break;
				case 7:
					$errmsg= '文件写入失败';break;
				default:
					$errmsg = '未知上传错误！';
			}
			return json(['status'=>0,'msg'=>$errmsg]);
		}
    }



	//浏览
	public function browser(){
		$pagenum = input('param.pagenum') ? input('param.pagenum') : 1;
		$where = [];
		if(input('param.gid') != '-1'){
			$where[] = ['gid','=',input('param.gid/d')];
		}
		if(input('param.keyword') != ''){
			$where[] = ['name','like','%'.input('param.keyword').'%'];
		}
		if(input('param.sort')==1){
			$sort = 'createtime asc';
		}elseif(input('param.sort')==3){
			$sort = 'name asc';
		}elseif(input('param.sort')==4){
			$sort = 'name desc';
		}else{
			$sort = 'createtime desc';
		}
		$count = Db::name('admin_upload')->field('id,name,url,type,size,createtime,width,height,dir')
            ->where('isdel',0)->where('platform','ht')->where($where)->where('type','<>','pem')->count();
		$rs = Db::name('admin_upload')->field('id,name,url,type,size,createtime,width,height,dir')
            ->where('isdel',0)->where('platform','ht')->where($where)->where('type','<>','pem')->order($sort)->page($pagenum,28)->select();
		$totalpage = ceil($count/28);
		return json(['status'=>1,'isdir'=>'0','data'=>$rs,'totalpage'=>$totalpage]);
	}
	//微信素材
	public function material(){
		set_time_limit(0);
		ini_set('memory_limit','1024M');
		$type = input('param.type') ? input('param.type') : 'image';
		$page = input('param.page') ? input('param.page') : 1;
		$access_token = \app\common\Wechat::access_token(aid,'mp');
		$url = 'https://api.weixin.qq.com/cgi-bin/material/get_materialcount?access_token='.$access_token;
		//dump($url);
		$rs = request_get($url);
		$rs = json_decode($rs,true);
		//dump($rs);
		$voice_count = $rs['voice_count'];
		$video_count = $rs['video_count'];
		$image_count = $rs['image_count'];
		$news_count = $rs['news_count'];
		$count = $rs[$type.'_count'];
		//获取素材
		$url = 'https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token='.$access_token;
		//dump($url);
		$data = [];
		$data['type'] = $type;
		$data['offset'] = ($page-1)*18;
		$data['count'] = 18;
		$rs = request_post($url,jsonEncode($data));
		$rs = json_decode($rs,true);
		//dump($rs);
		$artlist = [];
		if($rs['item']){
			$artlist = $rs['item'];
			foreach($artlist as $k=>$v){
				if($type=='voice' || $type=='video'){
					$material = Db::name('mp_material')->where('media_id',$v['media_id'])->where('type',$type)->where('endtime','>',time())->find();
					if(!$material){
						$rs = request_post('https://api.weixin.qq.com/cgi-bin/material/get_material?access_token='.$access_token,jsonEncode(['media_id'=>$v['media_id']]));
						if($type=='video'){
							$url = json_decode($rs,true)['down_url'];
							$name = date('Ym/d_His').rand(1000,9999).($type=='voice'?'.mp3':'.mp4');
							if (!file_exists(dirname(ROOT_PATH.'upload/'.$name))) {
								mk_dir(dirname(ROOT_PATH.'upload/'.$name));
							}
							file_put_contents(ROOT_PATH.'upload/'.$name,curl_get($url));
							$url = PRE_URL.'/upload/'.$name;
						}else{
							$name = date('Ym/d_His').rand(1000,9999).($type=='voice'?'.mp3':'.mp4');
							if (!file_exists(dirname(ROOT_PATH.'upload/'.$name))) {
								mk_dir(dirname(ROOT_PATH.'upload/'.$name));
							}
							file_put_contents(ROOT_PATH.'upload/'.$name,$rs);
							$url = PRE_URL.'/upload/'.$name;
						}
						$artlist[$k]['url'] = $url;
						Db::name('mp_material')->insert(['aid'=>aid,'url'=>$url,'media_id'=>$v['media_id'],'type'=>$type,'createtime'=>time()]);
					}else{
						$artlist[$k]['url'] = $material['url'];
					}
				}elseif($v['url'] && $v['media_id']){
					$material = Db::name('mp_material')->where('media_id',$v['media_id'])->where('type',$type)->where('endtime','>',time())->find();
					if(!$material){
						$picurl = \app\common\Pic::tolocal($v['url']);
						$artlist[$k]['url'] = $picurl;
						Db::name('mp_material')->insert(['aid'=>aid,'url'=>$picurl,'media_id'=>$v['media_id'],'type'=>$type,'createtime'=>time()]);
					}else{
						$artlist[$k]['url'] = $material['url'];
					}
				}
			}
		}
		return json(['code'=>0,'msg'=>'查询成功','count'=>$count,'data'=>$artlist]);
	}

	//删除
	public function deletefile(){
		$list = Db::name('admin_upload')->where('uid',$this->uid)->where('id','in',input('post.ids'))->select();
		if($list){
            Db::name('admin_upload')->where('uid',$this->uid)->where('id','in',input('post.ids'))->delete();
            foreach($list as $k=>$v){
                logic('OssLogic')->deletepic($v['url']);
            }
            return json(['status'=>1,'msg'=>'删除成功']);
        }
	}

	//图标库
	public function iconsvg(){

	}
	
	function sizecount($size){
		if($size >= 1073741824) {
			$size = round($size / 1073741824 * 100) / 100 . ' GB';
		} elseif($size >= 1048576) {
			$size = round($size / 1048576 * 100) / 100 . ' MB';
		} elseif($size >= 1024) {
			$size = round($size / 1024 * 100) / 100 . ' KB';
		} else {
			$size = $size . ' Bytes';
		}
		return $size;
	}

	public function ueditorconfig(){
		if(input('param.action') == 'config'){
			$config = [];
			$config['imageActionName'] = 'uploadimage';
			$config['imageFieldName'] = 'file';
			$config['imageUrlPrefix'] = '';
			return json($config);
		}elseif(input('param.action') == 'uploadimage'){
			return $this->index();
		}
	}

    public function uploadjstxt(){
        if (empty($_FILES)) {
            return json(['status'=>0,'msg'=>'请选择文件']);
        }
        foreach($_FILES as $field=>$file_v){
            //$ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
//            if(!preg_match('/^[A-Za-z0-9]+$/', file_get_contents($_FILES[$field]['tmp_name']))){
//                dump(preg_match('/^[A-Za-z0-9]+$/', file_get_contents($_FILES[$field]['tmp_name'])));exit;
//                return json(['status'=>0,'msg'=>'上传文件不合法,请重新上传']);
//            }
            $type = input('type')?:'';
            if($type){
                $path = '/extend/pay/'.$type.'/';
            }else{
                $path = '/extend/pay/';
            }
            if (!($_exists = file_exists($path))){
                $isMk = mkdir($path,775,true);
            }
            $file = request()->file($field);
            $validate = ['size'=>'5000000'];
            $info = $file->validate($validate)->move(ROOT_PATH.'/'.$path, false);
            if($info){
                $file_path = $path.'/'.$info->getFilename();
            }else{
                $result = [
                    'status' => 0,
                    'msg' => $file->getError(),
                    'data' => '',
                ];
                return json($result);
            }
        }
        return json(['status'=>1,'msg'=>'上传成功','file_path'=>$file_path,'field'=>$field]);
    }

}
